package com.wolfking.jeesite.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

@Slf4j
public class TransactionSynchronizationManagerUtils {
    public static void registerCommitCompletion(Runnable r) {
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCompletion(int status) {
                    if (status == TransactionSynchronization.STATUS_COMMITTED) {
                        try {
                            r.run();
                        } catch (Exception e) {
                            log.warn("", e);
                        }
                    }
                }
            });
        } else {
            r.run();
        }
    }


    public static void registerAfterCommit(Runnable r) {
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCommit() {
                    try {
                        r.run();
                    } catch (Exception e) {
                        log.warn("", e);
                    }
                }
            });
        } else {
            r.run();
        }
    }
}
